<template>
  <div class="equipment-detail">
    <div class="container">
      <!-- 头部 -->
      <div class="header">
        <div class="logo">铁甲二手机</div>
        <div class="title">二手工程机械交易平台</div>
      </div>
      
      <!-- 主要内容区域 -->
      <div class="content">
        <!-- 图片区域 -->
        <div class="image-section">
          <div class="card">
            <el-image 
              class="device-image"
              :src="deviceInfo.imageUrl" 
              :alt="deviceInfo.title"
              fit="cover"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon></el-icon>
                </div>
              </template>
            </el-image>
            
            <div class="disclaimer">
              说明：合影设备仅代表设备真实存在，真实可售
            </div>
          </div>
        </div>
        
        <!-- 信息区域 -->
        <div class="info-section">
          <div class="card">
            <div class="device-title">
            <div>
              {{ deviceInfo.year }}年{{ deviceInfo.brand }}牌{{ deviceInfo.typeName }}
            </div>
            <div class="wu">
            <div class="wuu">
               <!-- 实心五角星 -->
    <el-icon :size="30" :color="isFavorited ? '#ffcc00' : '#ccc'" @click="toggleFavorite" class="wu">
      <StarFilled class="wuu" />
    </el-icon>
    </div>
    </div>
            </div>
            <div class="device-id">(ID:{{ deviceInfo.equipmentId }})</div>
            
            <div class="price">{{ deviceInfo.price }}¥</div>
            
            <h3>设备原厂参数</h3> 
            <table class="specs-table">
              <tbody> 
              
              <tr>
                <td class="label">品牌</td>
                <td>{{ deviceInfo.brand }}</td>
             
                <td class="label">型号</td>
                <td>{{ deviceInfo.model }}</td>
              </tr>
              <tr>
                <td class="label">出厂年限</td>
                <td>{{ deviceInfo.year }}年</td>
              
                <td class="label">小时数</td>
                <td>{{ deviceInfo.hour }}</td>
              </tr>
              <tr>
                <td class="label">停放地</td>
                <td>{{ deviceInfo.location }}</td>
              
                <td class="label">更新时间</td>
                <td>{{ deviceInfo.updateTime }}</td>
              </tr>
              </tbody>
            </table>
            
           
          </div>
        </div>
      </div>
       <div class="contact-section">
        <el-card class="contact-card">
          <div class="but">
            <el-button class="contact-btn" type="primary" @click="yudin">我要预定</el-button>
            <!-- <el-button class="contact-btn" type="primary" @click="dialogVisible =true">砍价</el-button> -->
                        <el-button class="contact-btn" type="primary" v-if="butt" disabled>已砍</el-button>
                        <el-button class="contact-btn" type="primary" v-else @click="dialogVisible9">砍价</el-button>
  <!-- 静态模态框 -->
  <div class="modal-mask" v-if="visible123">
    <div class="modal-container">
      <!-- 标题 -->
      <div class="modal-header">
        <h2>用户协议与隐私政策</h2>
        <button class="close-btn" @click="handleClose123">×</button>
      </div>

      <!-- 固定协议内容 -->
      <div class="modal-body">
        <div class="agreement-content">
          <h3>《用户服务协议》</h3>
          
          <p><strong>第一条 总则</strong></p>
          <p>1.1 本协议是您与本公司之间的法律契约。</p>
          <p>1.2 使用服务即表示您同意接受本协议的全部条款。</p>

          <p><strong>第二条 服务内容</strong></p>
          <p>2.1 本公司提供XXXX平台服务。</p>
          <p>2.2 服务可能因系统维护而中断。</p>

          <p><strong>第三条 用户义务</strong></p>
          <p>3.1 您必须提供真实准确的个人信息。</p>
          <p>3.2 禁止利用服务从事违法活动。</p>

          <h3>《隐私政策》</h3>
          <p>我们承诺保护您的个人信息安全...</p>
        </div>
      </div>

      <!-- 固定操作按钮 -->
      <div class="modal-footer">
        <label class="agree-checkbox">
          <input type="checkbox" v-model="isAgreed">
          <span>我已阅读并同意以上协议</span>
        </label>
        <button 

          class="confirm-btn" 
          :class="{ disabled: !isAgreed }"
          :disabled="!isAgreed"
          @click="handleConfirm123"
        >
          同意并继续
        </button>
      </div>
    </div>
  </div>
            <!-- 模态框放在组件模板底部 -->
    <el-dialog v-model="dialogVisible" title="提示" width="60%">
         <el-form :model="form" label-width="120px">
      <el-form-item label="商品名称">
        <el-input v-model="form.typeName" disabled />
      </el-form-item>
      
      <el-form-item label="商品原价">
        <el-input v-model="form.price" disabled>
          <template #append>元</template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="砍价金额" prop="bargainPrice" required>
          <el-input v-model="form.vprice" placeholder="请输入砍价金额">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入您的砍价理由"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible6">取消</el-button>
        <el-button type="primary" @click="submitBargain">提交砍价</el-button>
      </span>
    </template>
    </el-dialog>
          </div>
        </el-card>
      </div>
      <div class="status-section">
        <el-card class="status-card">
          <div class="status-content">
              <div class="status-text">设备功能：{{ deviceInfo.typeDesc }}</div>
              <div class="status-text">设备状态：{{ deviceInfo.description }}</div>
          </div>
        </el-card>
      </div>
      <XM v-if="isReady"></XM>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref ,computed} from 'vue'
import { ElMessage } from 'element-plus'
import { Star, StarFilled } from '@element-plus/icons-vue';

import axios from 'axios';
import { useRoute,useRouter } from 'vue-router';
//导入pinia
import { useCounterStore } from '@/stores/counter'
//导入XM组件
import XM from '@/components/shouye/XM.vue'
const visible123 = ref(false);
const isAgreed = ref(false);

//下架
const xiajia = async () => { 
  const res = await axios.put(`advertisement/updateEquipment/${useCounterStore().equipmentId}`);
};

//确认按钮
const handleConfirm123 =async () => { 
  //生成订单
      await createOrder()
      //生成预定订单
      await createReservationOrder()
      //将设备状态改为下架
      await xiajia()
      //关闭模态框
      visible123.value = false;
      isAgreed.value = false;
      //跳转支付宝页面
      await zhifubao()
}
//关闭模态框
const handleClose123 = () => { 
  visible123.value = false;
};

//设置butt状态
const butt = ref(false)
    const isReady = ref(false)
    const router = useRouter()
    const route = useRoute()
    // 设备信息数据
    const deviceInfo = ref({})
    const equipmentId = ref()
    // 模态框

    //转Integer型
    onMounted(async() => {
      // 获取设备信息数据
      await getDeviceData();
      // 判断是否已经砍价
      await isBargain()


 // 主组件逻辑完成后，允许子组件渲染
      isReady.value = true;
      // 判断用户是否登录
      if (useCounterStore().token) {
        await isLogin();
      }
    })
    //生成订单
    const createOrder = async () => {
      const res = await axios.post(`/advertisement/addOrdd`,{
        equipmentId: useCounterStore().equipmentId,
        buyerId: useCounterStore().userId,
        sellerId: useCounterStore().userId2,
        orderAmount: deviceInfo.value.price,
        //金额的30%定金, 取整数
        depositAmount: Math.floor(deviceInfo.value.price * 0.3),
        //尾款
        balanceAmount: Math.floor(deviceInfo.value.price * 0.7),
        orderStatus: 0,
      })
      //设置订单id
      console.log('订单',res)
      useCounterStore().orderId = res.data.data.orderId
    }
  //生成预定订单
  const createReservationOrder = async () => {
      const res = await axios.post(`/advertisement/equipmentReservation/add`,{
        equipmentId: useCounterStore().equipmentId,
        userId: useCounterStore().userId,
        orderAmount: deviceInfo.value.price,
        orderId: useCounterStore().orderId,
        //金额的30%定金, 取整数
        reservationDeposit: Math.floor(deviceInfo.value.price * 0.3),
        reservationStatus: 0,
        //过期时间
        expireTime: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
        //有效时间
        reservationPeriod: 1
      })
      //设置预定id
      useCounterStore().reservationId = res.data.data.reservationId
    }
    //跳转支付宝支付页面
    const zhifubao = async () => {
      window.open(`http://localhost:9520/advertisement/alipay/pay?orderId=${useCounterStore().orderId}`)
    }
    //预定
    const yudin = async () => {
       if (!useCounterStore().token) {
        ElMessage.error('请先登录')
        return
      }{
        //判断是否预定过
        const res = await axios.post(`/advertisement/equipmentReservation/isEquipmentReservation`,{
          equipmentId: useCounterStore().equipmentId,
          userId: useCounterStore().userId
        })
        console.log('预定',res)
        if(res.data === '已存在'){
          ElMessage.error('已预定')
          return
        }
        else{
          ElMessage.success('请确认协议！进行付款')
          //是否同意协议
          visible123.value = true;
        }
    }
      
    }
//判断是否已经砍价
const isBargain = async () => {
      const res = await axios.post(`/advertisement/bargainintention/isBargainIntention`,{
        equipmentId: useCounterStore().equipmentId,
        userId: useCounterStore().userId
      })
      console.log('砍价',res)
      if(res.data === '已砍'){
        butt.value = true 
      }  
    }
      // 判断用户是否登录
    const isLogin = async () => {
       const res = await axios.post(`/advertisement/collection/isCollection`,
        {
          equipmentId: useCounterStore().equipmentId,
          userId: useCounterStore().userId
        })
      if (res.data.code === 20000) {
        // 设置收藏状态
        isFavorited.value = true;
      }
      else {
        // 未收藏
        isFavorited.value = false;
      }
    }


//获取设备信息数据
    const getDeviceData =async () => {
      //获取设备ID
        const equipmentId=route.params.equipmentId
        //设置全局变量的值
        useCounterStore().equipmentId=equipmentId
      const {data:response} = await axios.get(`/advertisement/equipment/${equipmentId}`)
      //设置卖家id全局变量的值
      useCounterStore().userId2=response.data.equipment.userId
      console.log('设备信息',useCounterStore().userId2)
       deviceInfo.value = response.data.equipment
       form.value = response.data.equipment
             //重新设置全局变量的值
             useCounterStore().equipmentId=route.params.equipmentId
             console.log('equipmentId',useCounterStore().equipmentId)
    }
   
   const isFavorited = ref(false);
//收藏功能
const toggleFavorite = async () => {
  //判断是否登录
  if (useCounterStore().token) {
    if(!isFavorited.value){
      const res = await axios.post('/advertisement/collection/addCollection', { equipmentId: useCounterStore().equipmentId ,userId: useCounterStore().userId });
        // 切换收藏状态
        isFavorited.value = !isFavorited.value;
        // 提示收藏成功
        ElMessage.success('收藏成功！');

    }
    else{
      const res = await axios.post('/advertisement/collection/cancelCollection', { equipmentId: useCounterStore().equipmentId ,userId: useCounterStore().userId });
        // 切换收藏状态
        isFavorited.value = !isFavorited.value;
        // 提示收藏成功
        ElMessage.success('取消收藏成功！');
    }
  }
  else {
    // 未登录，提示登录
    ElMessage.warning('请先登录！');
  }
};

//模态框砍价
const props = defineProps({
  originalPrice: {
    type: Number,
    default: 0
  }
  , remark: {
    type: String,
  }
})

const emit = defineEmits(['submit-success'])
//模态框数据
const dialogVisible = ref(false)
//砍价未登录
const dialogVisible9=async () => {
  if (!useCounterStore().token) {
    // 未登录，提示登录
    ElMessage.warning('请先登录！');
    return false
  }
  else {
    dialogVisible.value = true
  }
}
const form = ref({
})

// 计算最小砍价金额（原价的80%）
const minBargainPrice = computed(() => {
  return Math.round(props.originalPrice * 0.8 * 100) / 100
})

// 计算最大砍价金额（原价的95%）
const maxBargainPrice = computed(() => {
  return Math.round(props.originalPrice * 0.95 * 100) / 100
})

// 初始化默认砍价金额（取中间值）
const initDefaultPrice = () => {
  form.value.bargainPrice = Math.round((minBargainPrice.value + maxBargainPrice.value) / 2 * 100) / 100
}
//打开模态框
const openDialog = () => {
  initDefaultPrice()
  dialogVisible.value = true
}
//提交砍价
//是否登录
const submitBargain = async () => {
    console.log('收藏功能',useCounterStore().token)

  if(useCounterStore().token){
  //获取表单中的vprice字段和remark字段的数据
        const formData = form.value
  // 判断输入金额是否合法
  if (formData.vprice > formData.price || formData.vprice < 0.01) {
    ElMessage.error('请输入正确的砍价金额！')
    delete form.value.vprice
  }
  else {
    //将userId和equipmentId字段的数据添加进表单
    formData.userId = useCounterStore().userId
    formData.equipmentId = useCounterStore().equipmentId
    //修改formData中的price字段为originalPrice字段    
    formData.originalPrice = formData.price
    formData.intentionPrice = formData.vprice
    formData.bargainRemark = formData.remark
    // 提交砍价数据
    console.log('提交砍价数据',formData)
    const res = await axios.post('/advertisement/bargainintention/addBargainIntention', formData)
        // 提示提交成功
        ElMessage.success('提交成功！')
        dialogVisible.value = false
        // 提交成功后，将表单中的vprice字段的数据删除
        delete form.value.vprice
        delete form.value.remark
        //刷新按钮
        await isBargain()
  }
  }
else{
  ElMessage.warning('请先登录！')
}
}

//关闭模态框
const dialogVisible6=async () => {
  //关闭模态框
  dialogVisible.value = false
  //删除表单中的vprice字段的数据
  delete form.value.vprice
  delete form.value.remark
}
//暴露方法给父组件调用
defineExpose({
  openDialog
})
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}
.equipment-detail {
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
  min-height: 100vh;
  padding: 20px 0;
}
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}
.header .logo {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}
.header .title {
  margin-left: 15px;
  font-size: 18px;
  color: #606266;
}
.content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.image-section {
  flex: 1;
  min-width: 300px;
}
.info-section {
  flex: 1;
  min-width: 300px;
}
.card {
    height: 400px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}
.price {
  font-size: 28px;
  font-weight: bold;
  color: #f56c6c;
  margin: 15px 0;
}
.contact-btn {
  width: 50%;
  height: 40px;
  font-size: 18px;
  margin-top: 0px;
}
.specs-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}
.specs-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #ebeef5;
}
.specs-table tr:last-child td {
  border-bottom: none;
}
.specs-table .label {
  width: 20%;
  color: #909399;
  font-weight: 300;
}
.device-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 6px;
}
.disclaimer {
  background-color: #f0f9ff;
  border-left: 4px solid #409eff;
  padding: 10px 35px;
  margin: 30px 0;
  font-size: 14px;
  color: #606266;
}
.device-id {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
}
.device-title {
  font-size: 22px;
  font-weight: bold;
  /* margin: 10px 0; */
  display: flex;
}
@media (max-width: 768px) {
  .content {
    flex-direction: column;
  }
  .image-section, .info-section {
    width: 100%;
  }
}
.wu{
position: relative; /* 父容器设为 relative */
  width: 50%;
  height: 100%;
  border: 0px solid #eee; /* 仅示例，可移除 */
}
.wuu{
  position: absolute; /* 绝对定位 */
  top: -12px; /* 距离顶部 */
  right: 10px; /* 距离右侧 */
  cursor: pointer;
  z-index: 10; /* 确保在最上层 */
}
.but{
  display: flex;
  justify-content: space-between;

}
/* 基础样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  width: 80%;
  max-width: 600px;
  max-height: 70vh;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 头部样式 */
.modal-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  font-size: 24px;
  background: none;
  border: none;
  cursor: pointer;
  color: #999;
}

/* 内容区域 */
.modal-body {
  padding: 16px;
  overflow-y: auto;
  height: 400px; /* 固定高度 */
}

.agreement-content {
  line-height: 1.6;
  color: #666;
}

.agreement-content h3 {
  color: #333;
  border-left: 4px solid #1890ff;
  padding-left: 8px;
  margin: 20px 0 10px;
}

.agreement-content p {
  margin-bottom: 12px;
  text-align: justify;
}

/* 底部操作区 */
.modal-footer {
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.agree-checkbox {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
}

.agree-checkbox input {
  margin-right: 8px;
}

.confirm-btn {
  padding: 8px 24px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn.disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .modal-container {
    width: 95%;
    max-height: 80vh;
  }
  
  .modal-body {
    height: 60vh;
  }
}
</style>